﻿using ICSharpCode.SharpZipLib.Checksum;
using JSONDB.helpers;
using NLog;
using OPCService.Utils;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OPCService.Job
{
    class ReadTagFromExcel: IJob
    {
        private static readonly Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private static string jsonconfig = AppDomain.CurrentDomain.BaseDirectory + @ConfigHelper.ReadConfig("jsondb");
        private static string tagsExcel = AppDomain.CurrentDomain.BaseDirectory + @ConfigHelper.ReadConfig("excel"); //excel配置tag路径
        private static JsonDBHelper jsonDBHelper = new JsonDBHelper(jsonconfig);

        #region 入口
        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Run(async () =>
            {
                try
                {
                    await CreateOrUpdateTagsConfig();
                }
                catch (Exception e)
                {
                    logger.Error(e.Message);
                }
            });
        }
        #endregion

        #region 生成的tag配置表
        //判断是否更新生成的tag配置表，生成/Tags/config.json
        private async Task CreateOrUpdateTagsConfig()
        {
            string readBeforeChecksum = jsonDBHelper.GetFileCheckSum();
            string checksum = CheckSum.GetChecksum(HashingAlgoTypes.MD5, tagsExcel);
            if (checksum != readBeforeChecksum)
            {
                logger.Info("标签配置Excel已发生变化，更新配置json表,checksum:{}", checksum);
                await jsonDBHelper.UpdateFileCheckSum(checksum);
                Dictionary<string, DataTable> dicDt = Util.GetAllTags(); //从Excel读取各个sheet的tag信息
                if (dicDt.Count > 0)
                {

                    try
                    {
                        foreach (KeyValuePair<string, DataTable> kvp in dicDt)
                        {
                            DataTable dt = kvp.Value;
                            if (dt != null)
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    JSONDB.Model.Tag item = new JSONDB.Model.Tag();
                                    item.name = row[0].ToString();
                                    item.value = row[1].ToString();
                                    item.groupname = row[2].ToString();
                                    item.period = row[3]?.ToString();
                                    item.messure = row[4]?.ToString();
                                    item.opcname = kvp.Key;
                                    if (item.name == null || item.value == null)
                                    {
                                        continue;
                                    }

                                    await jsonDBHelper.ConfigSaveOrUpdate(item); //生成更新/Tags/config.json
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e);
                    }
                    finally
                    {}

                    await WriteTagToTxt(dicDt); //生成{opcserver_name}.txt文件
                }
            }
            else
            {
                logger.Info("标签配置Excel未发生变化，checksum:{}", checksum);
            }
        }
        #endregion

        #region 输出Tag到txt文档
        //输出Tag到txt文档
        private async Task WriteTagToTxt(Dictionary<string, DataTable> dicDt)
        {
            FileStream fs = null;
            StreamWriter writer = null;
            try
            {
                foreach (KeyValuePair<string, DataTable> kvp in dicDt)
                {
                    string filename = $"{ kvp.Key}.txt";
                    fs = new FileStream(@filename, FileMode.Create);
                    writer = new StreamWriter(fs, Encoding.Default);
                    {
                        foreach (DataRow r in kvp.Value.Rows)
                        {
                            if (r[1].ToString().Trim() != "") {
                                writer.WriteLine(r[1].ToString().Trim());
                            }
                        }
                    }
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
            finally
            {
                writer.Close();
                fs.Close();
            }
        }
        #endregion
    }
}
